package egovframework.npqs.pqi.mobile.activity;

import java.util.StringTokenizer;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.sds.BizAppLauncher.gov.aidl.GovController;
import com.sds.BizAppLauncher.gov.aidl.GovController.IGovCallback;

import egovframework.npqs.pqi.mobile.ActivityMain;
import egovframework.npqs.pqi.mobile.ActivityTest;
import egovframework.npqs.pqi.mobile.AppStatus;
import egovframework.npqs.pqi.mobile.R;
import egovframework.npqs.pqi.mobile.jsoncontent.ErrorItem;
import egovframework.npqs.pqi.mobile.jsoncontent.LoginItem;
import egovframework.npqs.pqi.mobile.jsonparser.LoginThread;
import egovframework.npqs.pqi.mobile.jsonparser.LoginThread.LoginThreadCallback;

public class LoginActivity extends Activity implements OnClickListener, LoginThreadCallback{
	//private static final String TAG = "LoginActivity";
	
	private Context context;
	private ImageButton loginBtn, cancelBtn;
	private AppStatus myapp;
 
	private LoginThread loginThread;
	private LoginItem mLoginItem;
	
	// 공통기반 초기화 activity
    private static final int ACTIVITY_LAUNCHER_INIT = 1;
	
	// SEMP 에 연결할 때 필요한 파라미터 userId 변수
    private String mUserId;
    // 호출 결과값 저장
    private String mResult;
    
    private TextView text_version;
    
	private final static int MSG_LOGIN_COMPLETED = 0;
	private final static int MSG_LOGIN_ERROR = 1;
	private final static int MSG_NETWORK_ERROR = 2;
	
	private static final int ACTIVITY_ATTACH_VIEWER = 11;
	//어플리케이션의 버젼
	public static String VERSION;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		
		context = LoginActivity.this;
		myapp = (AppStatus) getApplicationContext();
		
		//애플리케이션의 버젼 정보를 가져오는 로직
		PackageInfo pi;
		try {
			pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
			VERSION = pi.versionName;
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		text_version = (TextView)findViewById(R.id.text_version);
		text_version.setText(VERSION);
		
		loginBtn = (ImageButton)findViewById(R.id.login_btn);
		//cancelBtn = (ImageButton)findViewById(R.id.cancel_btn);
		
		loginBtn.setOnClickListener(this);
		//cancelBtn.setOnClickListener(this);
		
		myapp.startBroker(context);
        GovController.startGovActivityForResult(this, ACTIVITY_LAUNCHER_INIT); // initialize 함수 호출, 보안체크, 인증 시작
        Log.d("Launcher_libGov", "initialize 함수 호출");
        
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_btn:	// 로그인 버튼을 눌렀을 때	
			myapp.showDialogNo(context);
			loginThread = new LoginThread(context, this, mUserId);
			loginThread.start();
			break;

		default: 
			break;
		}
	}

	@Override
	protected void onPause() {
		overridePendingTransition(0, 0);	// 화면 전환시 애니메이션 없애기
		super.onPause();
	}

	// 로그인 성공시 콜백 함수
	@Override
	public void OnLoginCompleted(boolean isNetworkConntected,
			LoginItem loginItem, String message) {
		Log.i("message-->", "message-->"+message);
		if(null != message && !"".equals(message)){
			mResult = message;
			reesultToast();
		}
		
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}
		
		if(!isNetworkConntected){	// 네트워크 접속이 되어 있지 않을 때
			Message msg = handler.obtainMessage();
			msg.what = MSG_NETWORK_ERROR;
			handler.sendMessage(msg);
			return;
		}
		
		if(loginItem != null) {
			this.mLoginItem = loginItem;
			Message msg = handler.obtainMessage();
			msg.what = MSG_LOGIN_COMPLETED;
			handler.sendMessage(msg);
		}
	}

	// 로그인 실패시 콜백 함수
	@Override
	public void OnLoginError(ErrorItem errorItem) {
		if(myapp.dialog !=null && myapp.dialog.isShowing()) {
			myapp.dialog.dismiss();
		}

		Message msg = handler.obtainMessage();
		msg.what = MSG_LOGIN_ERROR;
		if(errorItem != null) {
			msg.obj = errorItem.getrDesc();
		}
		handler.sendMessage(msg);
	}
	
	/**
	 * 메시지를 보여주기 위한 Handler
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(final Message msg) {
			switch (msg.what) {
			case MSG_LOGIN_COMPLETED:
				
				AlertDialog.Builder a_builder = new AlertDialog.Builder(context);
				a_builder.setTitle("성공").setMessage("로그인에 성공하였습니다.").setCancelable(true)
						.setPositiveButton("확인", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								startActivity(new Intent(LoginActivity.this, ActivityMain.class));
					        	finish();
							}
						});
				a_builder.show();
				break;

			case MSG_LOGIN_ERROR:
				String errMsg = "";
				if(msg.obj == null){
					errMsg = "서버와의 연결에 실패하였습니다.";
				}else{
					errMsg = msg.obj.toString();	
				}
				
				myapp.utilm.ShowDialog(LoginActivity.this, "로그인실패", errMsg, 20);
				break;

			case MSG_NETWORK_ERROR:
				myapp.utilm.ShowDialog(LoginActivity.this, "실패", "네트워크에러", 20);

			default:
				break;
			}
		}
	};

    /**
     * 결과값 출력
     * @param result
     */
    private void reesultToast() {
        runOnUiThread(new Runnable() {

            public void run() {
                Toast toast = Toast.makeText(getApplicationContext(), mResult, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 50);
                toast.show();
            }
        });
    }

    /**
     * GPKI 인증 성공/실패 여부 확인
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if (null != intent) {
            switch (requestCode) {
                case ACTIVITY_LAUNCHER_INIT:
                    if (Activity.RESULT_OK == resultCode) {
                        //공통기반 initialize 성공. 행정용 애플리케이션 계속 실행
                        //Service Broker를 사용하기 위한 parameter인 userId 를 DN DATA에서 추출
                    	/*String signedData = intent.getExtras().getString("signedData");
                    	System.out.println("signedData->"+signedData.toString());*/
                        Log.d("Launcher_libGov", "공통 기반 initialize 성공");
                        String dn = intent.getExtras().getString("dn");
                        StringTokenizer st = new StringTokenizer(dn, ",");
                        String[] dnArray = new String[st.countTokens()];
                        int index = 0;
                        while (st.hasMoreElements()) {
                            dnArray[index++] = st.nextToken();
                        }
                        //dn값에서 userId를 추출하여 변수에 저장.
                        //mUserId = dnArray[0].toString();//substring(3, dnArray[0].length());
                        mUserId = dnArray[0].substring(3, dnArray[0].length());
                        AppStatus.setmUserId(mUserId);
                        
                        //Toast.makeText(getApplicationContext(), "user Id : "+mUserId, Toast.LENGTH_SHORT).show();
                    } else {
                        //공통기반 initialize 실패. 행정용 애플리케이션 종료
                        Log.d("Launcher_libGov", "공통 기반 initialize 실패");
                        finish();
                    }
                    break;
                    
                case ACTIVITY_ATTACH_VIEWER:
                	Log.d("ACTIVITY_ATTACH_VIEWER", "ACTIVITY_ATTACH_VIEWER");
                    break;
                    
                default:
                	Log.d("default", "공통 기반 default");
                    finish();
                    break;
            }
        }
    }

}
